$(document).ready(function() {
    "use strict";

    //获取验证码
    getCode();

    $(".zc-input input").on("input", function(){
        $(this).removeClass("error");
        $(this).parent().find("label.error").text("");
    });
});

//写cookie
function writeCookie(name, value, expires_in)
{
    var expire = new Date((new Date()).getTime() + expires_in);
    expire = "; expires=" + expire.toGMTString();
    document.cookie = name + "=" + encodeURIComponent(value) + expire+ "; path=/";
}

//回车触发登录按钮
$(document).keyup(function(event){
    if(event.keyCode ==13){
        $("#login-btn").trigger("click");
    }
});

function getCode(){
    $('#kaptchaImage').attr('src','/auth/login/verifyCode.jpg?' + Math.floor(Math.random() * 100));
}

function loginOnclick(){
    var fag = true;
    var mobileNo=$("#mobileNo").val();
    var password=$("#password").val();
    var codeInput=$("#code-input").val();
    $("#phone").text("");
    $("#mima").text("");
    $("#yanzhengma").text("");
    if(mobileNo==""){
        fag = false;
        $("#mobileNo").addClass("error");
        $("#phone").text("用户名不能为空！");
    }
    if(password==""){
        fag = false;
        $("#password").addClass("error");
        $("#mima").text("密码不能为空！");
    }
    if(codeInput==""){
        fag = false;
        $("#code-input").addClass("error");
        $("#yanzhengma").text("验证码不能为空！");
    }
    if(fag){
        login(mobileNo,password,codeInput);
    }
}

function login(mobileNo,password,codeInput){
    //var userType = $("input:radio[name='userType']:checked").val();
    var data={
                /*"clientId": "vimi8_com",*/
                "loginName": mobileNo,
                "loginSecret": password,
                "verifyCode": codeInput
              };
    $.ajax({
            type:'POST',
            url:"/auth/login/",
            data:JSON.stringify(data),
            contentType:"application/json",
            success: function (data) {
            console.log("data="+data);
                if(data.job!="org_corp"&&data.job!="org_super"&&data.job!="org_manager"){
                    $("#login-result").text("账号没有登录系统的权限！");
                    return;
                }
                   writeCookie("role",data.clientId,180*24*60*60*1000);
                   writeCookie("job",data.job,180*24*60*60*1000);
                   writeCookie("orgClass",data.clientOrgClass,180*24*60*60*1000);
                   localStorage.job = data.job;
                   
                	if(data.job=="org_corp"&&data.clientOrgClass=="org_ebb_entity"){
                            //如果是 经营实体的组织法人  只能添加产品 查询产品
                         window.location = "productManagerEntity.html";
                  	}else{
                     	 window.location = "index.html";
                    }



            },
            error: function (XMLHttpRequest, textStatus, errorThrown){
                //    XMLHttpRequest.readyState
                //    0 － （未初始化）还没有调用send()方法
                //    1 － （载入）已调用send()方法，正在发送请求
                //    2 － （载入完成）send()方法执行完成，已经接收到全部响应内容
                //    3 － （交互）正在解析响应内容
                //    4 － （完成）响应内容解析完成，可以在客户端调用了
                //    返回HHTP协议状态码 XMLHttpRequest.status

                //判断状态码
                if(XMLHttpRequest.readyState!=4){
                    console.log("XMLHttpRequest.readyState:"+XMLHttpRequest.readyState);
                    //提示Ajax请求失败
                }else if(XMLHttpRequest.status==401){
                    //跳转到登录页,带上登录后的跳转地址redirect_uri=???
                    // redirect_login();
                }else if(XMLHttpRequest.status==502){
                    //提示服务器忙

                }else if(XMLHttpRequest.status==404){
                    //提示页面未找到

                }else{
                    console.log("XMLHttpRequest.status:"+XMLHttpRequest.status);
                    //判断错误类型
                    var resp_error;
                    try {
                        resp_error=JSON.parse(XMLHttpRequest.responseText);
                    } catch (e) {
                    }
                    if(resp_error && resp_error.error && resp_error.errorDescription){
                        //根据错误类型,提示文字
                        console.log("resp_error.error:"+resp_error.error);
                        console.log("resp_error.errorDescription:"+resp_error.errorDescription);
                        if(resp_error.error=="invalid_param" && resp_error.errorDescription=="invalid verify code"){
                            $("#yanzhengma").text("验证码输入有误，请重新登录！");
                            $("#code-input").addClass("error");
                        }else{
                            $("#login-result").text("用户名或密码错误，请重新输入！");
                            $("#mobileNo").addClass("error");
                            $("#password").addClass("error");
                        }
                    }else{
                        //提示未知错误的
                        $("#login-result").text("用户名或密码错误，请重新输入！");
                        $("#mobileNo").addClass("error");
                        $("#password").addClass("error");
                    }
                }
            }
        });
}

//canvas动画
(function() {

    var width, height, largeHeader, canvas, ctx, circles, target, animateHeader = true;

    // Main
    initHeader();
    addListeners();

    function initHeader() {
        width = window.innerWidth;
        height = window.innerHeight;
        target = {x: 0, y: height};

        largeHeader = document.getElementById('large-header');
        largeHeader.style.height = height+'px';

        canvas = document.getElementById('canvas');
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');

        // create particles
        circles = [];
        for(var x = 0; x < width*0.5; x++) {
            var c = new Circle();
            circles.push(c);
        }
        animate();
    }

    // Event handling
    function addListeners() {
        window.addEventListener('scroll', scrollCheck);
        window.addEventListener('resize', resize);
    }

    function scrollCheck() {
        if(document.body.scrollTop > height) animateHeader = false;
        else animateHeader = true;
    }

    function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        largeHeader.style.height = height+'px';
        canvas.width = width;
        canvas.height = height;
    }

    function animate() {
        if(animateHeader) {
            ctx.clearRect(0,0,width,height);
            for(var i in circles) {
                circles[i].draw();
            }
        }
        requestAnimationFrame(animate);
    }

    // Canvas manipulation
    function Circle() {
        var _this = this;

        // constructor
        (function() {
            _this.pos = {};
            init();
            //console.log(_this);
        })();

        function init() {
            _this.pos.x = Math.random()*width;
            _this.pos.y = height+Math.random()*100;
            _this.alpha = 0.1+Math.random()*0.3;
            _this.scale = 0.1+Math.random()*0.3;
            _this.velocity = Math.random();
        }

        this.draw = function() {
            if(_this.alpha <= 0) {
                init();
            }
            _this.pos.y -= _this.velocity;
            _this.alpha -= 0.0005;
            ctx.beginPath();
            ctx.arc(_this.pos.x, _this.pos.y, _this.scale*10, 0, 2 * Math.PI, false);
            ctx.fillStyle = 'rgba(255,255,255,'+ _this.alpha+')';
            ctx.fill();
        };
    }

})();